package hot100.logos71To80;

/**
 * @author logos
 * date 2025/7/17 12:31
 * @version v1.0
 * @Package hot100.logos71To80
 */
public class logos71 {

    /**
     * 71. 字符串解码
     * https://leetcode.cn/problems/decode-string/description/?envType=study-plan-v2&envId=top-100-liked
     */

    class Solution {
        private int where;

        public String decodeString(String s) {
            char[] sArr = s.toCharArray();
            where = 0;
            return f(sArr, 0);
        }

        private String f(char[] s, int i) {
            StringBuilder sb = new StringBuilder();
            int cur = 0;
            while (i < s.length && s[i] != ']') {
                if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) {
                    sb.append(s[i++]);
                } else if (s[i] >= '0' && s[i] <= '9') {
                    cur = cur * 10 + s[i++] - '0';
                } else {
                    String tmp = get(cur, f(s, i + 1));
                    sb.append(tmp);
                    cur = 0;
                    i = where + 1;
                }
            }
            where = i;
            return sb.toString();
        }

        private String get(int cur, String str) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < cur; j++) {
                sb.append(str);
            }
            return sb.toString();
        }
    }
}
